<template>
  <el-card class="w-full pt-[5px]">
    <!-- <el-radio-group v-model="planType">
      <el-radio-button label="全部" value="" />
      <el-radio-button label="审批通过" value="0" />
      <el-radio-button label="审批不通过" value="1" />
      <el-radio-button label="审批中" value="2" />
    </el-radio-group> -->
    <el-form :model="searchForm" class="mt-[20px]" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="知识产权编号" class="mb-[0px]">
            <el-input v-model="searchForm.code" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="成果名称">
            <el-input v-model="searchForm.name" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen">更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="getList(1)">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-[20px]" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="成果联系人">
            <el-input v-model="searchForm.txAuthor" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="第一完成人">
            <el-input v-model="searchForm.firstAuthorName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="知识产权类型" class="mb-[0px]">
            <CustomTreeSelect placeholder="知识产权类型" v-model="searchForm.typeId" valueKey="code" labelKey="name"
              :isFetch="false" :dataList="zscqList" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button type="primary" v-equalRole="['biz_kyry', 'biz_kycgly']" @click="handleAdd">
        <el-icon class="mr-[5px]">
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-button @click="handleDel">
        <el-icon>
          <DeleteFilled />
        </el-icon>
        删除
      </el-button>
      <el-button v-equalRole="['biz_kycgly', 'biz_kyms']" @click="exportVisible = true">
        <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
      </el-button>
    </div>
    <el-table :data="tableData" class="w-full" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" :selectable="checkSelectable" />
      <el-table-column prop="code" label="知识产权编号" />
      <el-table-column prop="name" label="成果名称">
        <template #default="scope">
          <el-link type="primary" @click="viewItem(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="typeId" label="知识产权类型">
        <template #default="scope">
          <Feedback :id="scope.row.typeId" :list="zscqList">
          </Feedback>
        </template>
      </el-table-column>
      <el-table-column prop="unitId" label="所属单位">
        <template #default="scope">
          <Feedback :id="scope.row.unitId" :list="zcgsdwList" :mapping="['codeColumn', 'valueColumn']">
          </Feedback>
        </template>
      </el-table-column>
      <el-table-column prop="txAuthor" label="成果联系人" :formatter="formatAuthorName" />
      <el-table-column prop="txAuthorTel" label="联系人电话" />
      <el-table-column prop="firstAuthorName" label="第一完成人" />
      <el-table-column prop="authorTel" label="完成人电话" />
      <el-table-column label="研发起止时间 " width="200">
        <template #default="scope"> {{ scope.row.researchStartdate }}-{{ scope.row.researchEnddate }} </template>
      </el-table-column>
      <el-table-column prop="checkstatus" label="审核状态">
        <template #default="scope">
          <Feedback :id="scope.row.checkstatus" :list="shztList"> </Feedback>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" plain v-show="editRole(scope.row.checkstatus)"
            @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="success" v-show="scope.row.isAuditor" v-equalRole="['biz_kycgly', 'biz_kyms']" size="small"
            @click="handleCheck(scope.row.id, scope.row.processInstanceId)" plain>
            审核
          </el-button>
          <el-button type="warning" size="small" v-equalRole="['biz_kyry']" plain @click="handleCancel(scope.row)"
            :loading="scope.row.processLoading" v-show="scope.row.checkstatus == 1">撤销</el-button>
          <el-button type="danger" size="small" v-equalRole="['biz_kyry', 'biz_kyms']"
            v-show="(scope.row.checkstatus == '-1' || scope.row.checkstatus == '3') && checkSelectable(scope.row)" plain
            @click="del(scope.row)">删除</el-button>
          <el-button type="danger" size="small" v-show="checkSelectable(scope.row)" v-equalRole="['biz_kycgly']" plain
            @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <pagination v-show="total > 0" :total="total" v-model:page="pageInfo.pageNum" v-model:limit="pageInfo.pageSize"
        @pagination="getList" />
    </div>
  </el-card>
  <EditModal v-model="editModelVisible" ref="EditModalRef" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
    :typeIdList="zscqList" :manifestationIdList="manifestationIdList" :matureIdList="matureIdList"
    :advancedIdList="advancedIdList" :domainIdList="domainIdList" :sshyList="sshyList" :obtainIdList="obtainIdList"
    :supportIdList="supportIdList" :transforIdList="transforIdList" @callBack="callBackFun">
  </EditModal>
  <viewModal v-model="ViewdialogVisible" ref="viewModalRef" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
    :typeIdList="zscqList" :manifestationIdList="manifestationIdList" :matureIdList="matureIdList"
    :advancedIdList="advancedIdList" :domainIdList="domainIdList" :sshyList="sshyList" :obtainIdList="obtainIdList"
    :supportIdList="supportIdList" :transforIdList="transforIdList" />
  <CheckModal v-model="CheckModalVisible" ref="checkModalRef" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
    :typeIdList="zscqList" :manifestationIdList="manifestationIdList" :matureIdList="matureIdList"
    :advancedIdList="advancedIdList" :domainIdList="domainIdList" :sshyList="sshyList" :obtainIdList="obtainIdList"
    :supportIdList="supportIdList" :transforIdList="transforIdList" @callBack="callBackFun" />
  <exportModal v-model="exportVisible" :selectList="exportList" title="科研成果转化" @callBack="callBackMet" />
</template>

<script setup>
import { onMounted } from 'vue'
import { getCategory } from '@/api/system/category'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getkycgzhList, kycgzhDel, getkycgzhInfo } from '@/api/achievement/zscq'
import EditModal from './EditModal.vue'
import viewModal from './viewModal.vue'
import { exportFile } from '@/api/fee/common.js'
import exportModal from '@/components/export'
import { downloadFile } from '@/utils/main'
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import useCategoryStore from '@/store/modules/category'
import CheckModal from "./CheckModal.vue";
import { cancelProcess } from "@/api/project/common";
import Cookies from 'js-cookie'
const categoryStore = useCategoryStore()
const {
  shztList,
  zcgsdwList,
  xlList,
  zcList,
  zscqList,
  manifestationIdList,
  matureIdList,
  advancedIdList,
  domainIdList,
  sshyList,
  obtainIdList,
  supportIdList,
  transforIdList,
} = storeToRefs(categoryStore) // 解构状态
const {
  getshztList,
  getzcgsdwList,
  getxlList,
  getzcList,
  getsshyList,
  getzscqList,
  getManifestationIdList,
  getMatureIdList,
  getAdvancedIdList,
  getDomainIdList,
  getObtainIdList,
  getSupportIdList,
  getTransforIdList,
} = categoryStore // 解构方法

const router = useRouter()
const planType = ref('')
const searchFormOpen = ref(false)
const editModelVisible = ref(false)
const viewSbModalVisible = ref(false)
const exportVisible = ref(false)
const CheckModalVisible = ref(false);

const searchForm = ref({
  name: '',
  code: '',
  txAuthor: '',
  firstAuthorName: '',
  typeId: [],
})
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
})

const total = ref(0)
const tableData = ref([])
const EditModalRef = ref(null)

//点击新增
const handleAdd = () => {
  editModelVisible.value = true
  EditModalRef.value.getKyryInfo();
}


//点击编辑
const handleEdit = (i) => {
  getkycgzhInfo(i.id).then((res) => {
    console.log(res)
    if (res.code == 200) {
      // searchForm.value = res.data
      editModelVisible.value = true
      EditModalRef.value.getFrom(res.data)
    }
  })
}
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
//点击删除
const handleDel = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  } else {
    ElMessageBox.confirm('是否确认删除？', '提示', {
      type: 'warning',
    }).then(() => {
      let ids = multipleSelection.value.map((item) => item.id)
      ids = ids.join(',')
      kycgzhDel(ids).then((res) => {
        if (res.code == 200) {
          getList()
          ElMessage.success('删除成功')
        }
      })
    })
  }
}


const formatAuthorName = (row, column, cellValue, index) => {
  return JSON.parse(cellValue).name
}

const initList = () => {
  getList()
}

const valueDate1 = ref('')

const reset = () => {
  valueDate1.value = ''
  searchForm.value = {
    name: '',
    code: '',
    txAuthor: '',
    firstAuthorName: '',
    typeId: [],
  }
}
/**
 * 获取专利列表数据
 *
 * @returns 无返回值
 */
const getList = async (i) => {
  if (i == 1) {
    pageInfo.value.pageNum = 1
  }
  console.log(valueDate1.value, 'valueDate1')
  let parms = {
    ...searchForm.value,
    ...pageInfo.value,
  }
  parms.typeId = searchForm.value.typeId.join(',')
  let res = await getkycgzhList(parms)
  if (res.code == 200) {
    tableData.value = res.rows
    tableData.value.forEach((item) => {
      Reflect.set(item, "processLoading", false);
    });
    total.value = res.total
  }
}
const callBackFun = () => {
  getList()
}
const del = (i) => {
  ElMessageBox.confirm('确认！删除这条数据?', '提醒', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      kycgzhDel(i.id).then((res) => {
        if (res.code == 200) {
          getList()
          ElMessage.success('删除成功')
        }
      })
    })
    .catch(() => { })
}


const editRole = (i) => {
  if (Cookies.get("role-key") == 'biz_kyry') {
    if (i == '-1' || i == '3') {
      return true;
    } else {
      return false;
    }
  } else if (Cookies.get("role-key") == 'biz_kyms') {
    if (i == '-1' || i == '3' || i == '1') {
      return true;
    } else {
      return false;
    }
  } else if (Cookies.get("role-key") == 'biz_kycgly') {
    return true;
  } else {
    return false;
  }

}


const checkModalRef = ref();
//点击审核
const handleCheck = (id, processId) => {
  getkycgzhInfo(id).then((res) => {
    if (res.code == 200) {
      CheckModalVisible.value = true;
      checkModalRef.value.getRuleForm(res.data, processId);
    }
  });
};
// const processLoading = ref(false);
//点击撤销
const handleCancel = async (i) => {
  try {
    i.processLoading = true;
    const res = await cancelProcess(i.processInstanceId);
    if (res.data) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      initList();
    } else {
      ElMessage({
        message: "操作失败！",
        type: "warning",
      });
    }
    i.processLoading = false;
  } catch (error) {
    console.log(error);
    i.processLoading = false;
  }
};

const ViewdialogVisible = ref(false)
const viewModalRef = ref(null)

const viewItem = (i) => {
  getkycgzhInfo(i.id).then((res) => {
    if (res.code == 200) {
      ViewdialogVisible.value = true
      viewModalRef.value.getRuleForm(res.data)
    }
  })
}

const exportList = [
  {
    lable: '知识产权编号',
    value: 'code',
    isSelect: true,
  },
  {
    lable: '成果名称',
    value: 'name',
    isSelect: true,
  },
  {
    lable: '知识产权类型',
    value: 'typeId',
    isSelect: true,
  },
  {
    lable: '成果联系人',
    value: 'txAuthor',
    isSelect: false,
  },
  {
    lable: '联系人电话',
    value: 'txAuthorTel',
    isSelect: true,
  },
  {
    lable: '所属单位',
    value: 'unitId',
    isSelect: true,
  },
  {
    lable: '第一完成人',
    value: 'firstAuthorName',
    isSelect: true,
  },
  {
    lable: '完成人电话',
    value: 'authorTel',
    isSelect: true,
  },
  {
    lable: '研发起止时间',
    value: 'researchDate',
    isSelect: false,
  },
  {
    lable: '审核状态',
    value: 'checkstatus',
    isSelect: false,
  },
]

const callBackMet = (i) => {
  console.log(i, 'callBackMet')
  let parms = {
    selectedColumns: i.map((item) => item.prop),
    ...searchForm.value,
  }
  parms.typeId = searchForm.value.typeId.join(',')
  exportFile('/achievement/transform/export', parms).then((res) => {
    downloadFile(res, `科研成果转化清单_${new Date().getTime()}.xlsx`)
  })
}

onMounted(() => {
  initList()
})


const checkSelectable = (row, index) => {
  return row.checkstatus != '1';
}



onMounted(() => {
  if (!shztList.value.length) {
    getshztList()
  }
  if (!zcgsdwList.value.length) {
    getzcgsdwList()
  }
  if (!sshyList.value.length) {
    getsshyList()
  }
  if (!xlList.value.length) {
    getxlList()
  }
  if (!zcList.value.length) {
    getzcList()
  }

  if (!zscqList.value.length) {
    getzscqList()
  }
  if (!manifestationIdList.value.length) {
    getManifestationIdList()
  }
  if (!matureIdList.value.length) {
    getMatureIdList()
  }
  if (!domainIdList.value.length) {
    getDomainIdList()
  }
  if (!advancedIdList.value.length) {
    getAdvancedIdList()
  }
  if (!obtainIdList.value.length) {
    getObtainIdList()
  }
  if (!supportIdList.value.length) {
    getSupportIdList()
  }
  if (!transforIdList.value.length) {
    getTransforIdList()
  }
  initList()
})
</script>
